package zhihuilan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import zhihuilan.common.utils.MD5EncryptionUtils;
import zhihuilan.common.utils.ToolsUtils;
import zhihuilan.entity.*;
import zhihuilan.mapper.*;
import zhihuilan.params.query.MyStaffQueryParam;
import zhihuilan.service.MyCircleService;
import zhihuilan.service.MySearchService;
import zhihuilan.service.MyStaffService;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;

/**
 * 用户数据 服务实现
 *
 * @author ruoyi
 */
@Service
public class MyStaffServiceImpl extends ServiceImpl<MyStaffMapper, MyStaff> implements MyStaffService {
    private final static String tbName = "staff";

    @Resource
    private MySearchService mySearchService;

    @Resource
    private MyCircleMapper myCircleMapper;

    @Resource
    private MyStaffShopGoodsMapper myStaffShopGoodsMapper;

    @Resource
    private MyCategoryStaffMapper myCategoryStaffMapper;

    @Resource
    private MyCircleDiscussMapper myCircleDiscussMapper;

    @Override
    public List<MyStaff> selectMyStaffList(MyStaffQueryParam queryParam) {
        QueryWrapper<MyStaff> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(queryParam)) {
            if (!ObjectUtils.isEmpty(queryParam.getId())) {
                queryWrapper.eq("id", queryParam.getId());
            }
            if (!ObjectUtils.isEmpty(queryParam.getGuid())) {
                queryWrapper.eq("guid", queryParam.getGuid());
            }
            if (!ObjectUtils.isEmpty(queryParam.getName())) {
                queryWrapper.like("userreal", queryParam.getName());
            }
        }
        queryWrapper.last("limit 1000,1000");
        List<MyStaff> result = this.baseMapper.selectList(queryWrapper);
        return result;
    }

    @Override
    public MyStaff selectMyStaffById(Integer id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public MyStaff selectMyStaffByGuid(String guid) {
        if (ObjectUtils.isEmpty(guid))
            return null;
        QueryWrapper<MyStaff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("guid", guid);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public MyStaff selectMyStaffByTel(String tel) {
        if (ObjectUtils.isEmpty(tel))
            return null;
        QueryWrapper<MyStaff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone", tel);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Transactional
    @Override
    public MyStaff addEntity(MyStaff entity) {
        Boolean result = save(entity);
        if (result) {
            long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
            //用户保存成功之后，获取到保存成功的ID，用于计算其他字段数据并更新；
            String guid = MD5EncryptionUtils.md5Encrypt(entity.getId() + "_" + timestamp);
            entity.setGuid(guid);
            entity.setNickname("用户：" + entity.getId());
            entity.setUserreal("用户：" + entity.getId());
            this.updateEntity(entity);
            return entity;
        } else {
            return null;
        }
    }

    @Override
    public MyStaff updateEntity(MyStaff entity) {
        Boolean result = updateById(entity);
        if (result) {
            return entity;
        } else {
            return null;
        }
    }

    @Transactional
    @Override
    public MyStaff updateEntityToShop(MyStaff entity) {
        int result = this.baseMapper.updateById(entity);
        this.updateMySearchInfo(entity);
        if (result > 0) {
            return entity;
        } else {
            return null;
        }
    }

    /**
     * 新增、更新、删除查询表相关信息；
     *
     * @param entity 线缆圈信息
     * @return 返回操作成功或者失败！
     * @author chenk
     * @date 2025年3月4日 15:50:33
     */
    private Boolean updateMySearchInfo(MyStaff entity) {
        MySearch mySearch = new MySearch();
        mySearch.setLng(entity.getLng());
        mySearch.setLat(entity.getLat());
        mySearch.setRegion(entity.getRegion());
        mySearch.setLnggd(entity.getLnggd());
        mySearch.setLatgd(entity.getLatgd());
        mySearch.setDistrictid(entity.getDistrictid());
        mySearch.setDistrictid1(entity.getDistrictid1());
        mySearch.setDistrictid2(entity.getDistrictid2());
        mySearch.setAddress(entity.getAddress());
        mySearch.setAddress1(entity.getAddress1());
        mySearch.setAddress2(entity.getAddress2());
        mySearch.setFid(0);
        mySearch.setTbName("staff_shop_goods");
        mySearch.setStaffId(entity.getId());
        // db('search')->where(array("staff_id"=>$member["id"],"tb_name"=>"staff_shop_goods","fid"=>0))->update($s);
        this.mySearchService.updateEntity(mySearch);

        // $info = db("staff")->where(array("id"=>$member['id']))->find();
        mySearch.setUtype(entity.getCategoryUtype());
        mySearch.setFid(null);
        mySearch.setTbName("circle");
        mySearch.setStaffId(entity.getId());
        this.mySearchService.updateEntity(mySearch);

        return true;
    }

    @Transactional
    @Override
    public Boolean deleteMyStore(MyStaff staff) throws RuntimeException {
        if (ObjectUtils.isEmpty(staff.getId())) {
            return false;
        }
        try {
            staff.setStype(0);
            staff.setLogo("");
            staff.setMobile("");
            staff.setTitle("");
            staff.setLng("");
            staff.setLat("");
            staff.setLnggd("");
            staff.setLatgd("");
            staff.setRegion("");
            staff.setDistrictid("");
            staff.setDistrictid1("");
            staff.setDistrictid2("");
            staff.setAddress("");
            staff.setAddress1("");
            staff.setAddress2("");
            staff.setCategoryUtype(0);
            this.baseMapper.updateById(staff);

            mySearchService.deleteByTableAndFid("circle", null, null, staff.getId());
//        db("circle")->where(array("staff_id"=>$info["id"],"status"=>1))->where(" utype!=1 ")->update(array("status"=>0));
            QueryWrapper<MyCircle> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("staff_id", staff.getId());
            queryWrapper.ne("utype", 1);
            MyCircle circle = new MyCircle();
            circle.setStatus(0);
            int count = myCircleMapper.update(circle, queryWrapper);
            mySearchService.deleteByTableAndFid("staff_shop_goods", null, 0, staff.getId());

            QueryWrapper<MyStaffShopGoods> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("staff_id", staff.getId());
            deleteWrapper.eq("shopid", 0);
            deleteWrapper.eq("status", 1);
            myStaffShopGoodsMapper.delete(deleteWrapper);

            QueryWrapper<MyCategoryStaff> categoryDeleteWrapper = new QueryWrapper<>();
            categoryDeleteWrapper.eq("staff_id", staff.getId());
            categoryDeleteWrapper.eq("status", 2);
            myCategoryStaffMapper.delete(categoryDeleteWrapper);

            QueryWrapper<MyCircleDiscuss> circleDiscussWrapper = new QueryWrapper<>();
            circleDiscussWrapper.eq("staff_id", staff.getId());

            myCircleDiscussMapper.delete(circleDiscussWrapper);
            circleDiscussWrapper.eq("pstaffid", staff.getId());
            myCircleDiscussMapper.delete(circleDiscussWrapper);
        } catch (RuntimeException e) {
            throw new RuntimeException("删除个人店铺的时候报错了；数据即将回滚！" + e.getMessage());
        }
        return true;
    }
}
